import binascii
import random
import uuid

from redis.client import Redis

mconn = Redis(host="192.168.35.110", port=6379, db=0, decode_responses=True)


def shard_key(base, key, total_element, shard_size):
    if isinstance(key, (int)) or key.isdigit():
        shard_id = int(str(key), 10) // shard_size
    else:
        shards = 2 * total_element // shard_size
        shard_id = binascii.crc32(key.encode()) % shards
    return "%s%s" % (base, shard_id)


def shard_sadd(conn, base, member, total_element, shard_size):
    shard = shard_key(base, 'x' + member, total_element, shard_size)
    return conn.sadd(shard, member)


def get_code(country, state):
    cindex = random.randint(0, 100)
    sindex = random.randint(0, 1000)
    c = chr(cindex) + chr(sindex)
    return c


USERS_PRE_SHARD = 2 ** 10


def devmod(user_id, USERS_PRE_SHARD):
    shardid = int(user_id / USERS_PRE_SHARD)
    offset = user_id % USERS_PRE_SHARD
    return shardid, offset


def set_location(conn, user_id, country, state):
    code = get_code(country, state)
    shard_id, position = devmod(user_id, USERS_PRE_SHARD)
    offset = position * 2
    pipe = conn.pipeline(False)
    pipe.setrange('location:%s' % shard_id, offset, code)
    tkey = str(uuid.uuid4())
    pipe.zadd(tkey, {'max': user_id})
    pipe.zunionstore('location:max', [tkey, 'location:max'], aggregate='max')
    pipe.delete(tkey)
    pipe.execute()


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # id = int(str(uuid.uuid4()).replace('-', '')[:15], 16)
    # print(shard_sadd(mconn, 'visitor:', str(id), 10240, 1024))
    user_id = random.randint(0, 2 ** 10 * 100)
    shard_id, position = devmod(user_id, USERS_PRE_SHARD)
    print(shard_id, position)
    set_location(mconn, user_id, '', '')
    offset = position * 2
    print(mconn.getrange('location:%s' % shard_id, offset, offset+2))

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
